package com.ape.service.impl;

import com.ape.bean.PageResponse;
import com.ape.convert.SysUserConvert;
import com.ape.entity.po.SysUserPo;
import com.ape.entity.req.PageSysUserReq;
import com.ape.dao.SysUserDao;
import com.ape.service.SysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * (SysUser)表服务实现类
 *
 * @author makejava
 * @since 2023-12-04 20:36:44
 */
@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserDao sysUserDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    //spring注解的方式实现redis缓存
    @Cacheable(cacheNames = "sysUserService",key="'queryUserById'+#id")
    public SysUserPo queryById(Long id) {
        return this.sysUserDao.queryById(id);
    }

    /**
     * 分页查询
     * @return 查询结果
     */
    @Override
    public PageResponse<SysUserPo> queryByPage(PageSysUserReq pageSysUserReq) {
        SysUserPo sysUserPo = SysUserConvert.INSTANCE.convertReqToPo(pageSysUserReq);
        BeanUtils.copyProperties(pageSysUserReq,sysUserPo);
        PageResponse<SysUserPo> pageResponse = new PageResponse<>();
        pageResponse.setCurrent(pageSysUserReq.getPageNo());
        pageResponse.setPageSize(pageSysUserReq.getPageSize());
        Long pageStart = (pageSysUserReq.getPageNo()-1)* pageSysUserReq.getPageSize();
        long total = this.sysUserDao.count(sysUserPo);
        List<SysUserPo> sysUserList = this.sysUserDao.queryAllByLimit(sysUserPo, pageStart, pageSysUserReq.getPageSize());
        pageResponse.setTotal(total);
        pageResponse.setRecords(sysUserList);
        return pageResponse;
    }

    /**
     * 新增数据
     *
     * @param sysUser 实例对象
     * @return 实例对象
     */
    @Override
    public SysUserPo insert(SysUserPo sysUser) {
        this.sysUserDao.insert(sysUser);
        return sysUser;
    }

    /**
     * 修改数据
     *
     * @param sysUser 实例对象
     * @return 实例对象
     */
    @Override
    public SysUserPo update(SysUserPo sysUser) {
        this.sysUserDao.update(sysUser);
        return this.queryById(sysUser.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.sysUserDao.deleteById(id) > 0;
    }
}
